#include <uv.h>
#include <stdio.h>
#include <string.h>
#include <string>


struct write_request {
    uv_udp_send_t req;
    char buff[15];

    write_request(const char *data, size_t len) {
        memset(buff, 0x00, 15);
        snprintf(buff, 14, "%s", data);
    }
};

uv_udp_t udp_handle;
uv_timer_t timer;
write_request req("hello world!", 15);

static void udp_send_cv(uv_udp_send_t* req, int status) {
    if (status != 0)
        fprintf(stderr, "send message error:%s!\n", uv_err_name(status));
    printf("udp send\n");
}

static void timer_cb(uv_timer_t* ) {
    uv_buf_t buf = uv_buf_init(req.buff, strlen(req.buff));

    struct sockaddr_in addr;
    memset(&addr, 0x00, sizeof(addr));
    int ret = uv_ip4_addr("192.168.2.246", 10000, &addr);
    if (ret != 0) {
        fprintf(stderr, "addr convert error: %s\n", uv_err_name(ret));
        return;
    }

    ret = uv_udp_send(&req.req, &udp_handle, &buf, 1, (const sockaddr *)&addr, udp_send_cv);
    if (ret != 0)
        fprintf(stderr, "send msg error: %s\n", uv_err_name(ret));

    printf("timer cb\n");
}

int main(int argc, const char **argv) {
    uv_loop_t *loop = uv_default_loop();

    int ret = uv_udp_init(loop, &udp_handle);
    if (ret != 0) {
        fprintf(stderr, "udp handle init error: %s\n", uv_err_name(ret));
        return ret;
    }

    ret = uv_timer_init(loop, &timer);
    if (ret != 0) {
        fprintf(stderr, "timer handle init error: %s\n", uv_err_name(ret));
        return ret;
    }

    ret = uv_timer_start(&timer, timer_cb, 1000, 1000);
    if (ret != 0) {
        fprintf(stderr, "timer start error: %s\n", uv_err_name(ret));
        return ret;
    }

    uv_run(loop, UV_RUN_DEFAULT);
    return 0;
}
